package Volume1.ch5;

import java.lang.reflect.Array;

/**
 * 通过反射方法进行数组的扩展
 * @Auther jacob
 * @Date 2020/8/7 20:06
 */
public class CopyOfTest {

    /**
     * 不正确的方法
     * @param a 数组元素
     * @param newLength 新数组长度
     * @return 扩展后的数组，但是扩展后的数组类型为Object类，与原来的数组a的类型不一致
     */
    public static Object[] badCopyOf(Object[] a, int newLength){
        Object[] newArray = new Object[newLength];
        System.arraycopy(a,0,newArray, 0, Math.min(a.length, newLength));
        return newArray;
    }

    public static Object goodCopyOf(Object a, int newLength){
        Class cl = a.getClass();
        if (!cl.isArray()){
            return null;
        }

        Class componentType = cl.getComponentType();
        int length = Array.getLength(a);
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(a,0,newArray,0, Math.min(length, newLength));
        return newArray;
    }

    public static void main(String[] args) {
        String[] str = {"abc", "def", "ghk"};
        System.out.println("badCopyOf中原数组大小 = " + str.length);
//        String[] newStrBadCopy = (String[]) badCopyOf(str, 10); // 此处会报异常
        Object[] newStrBadCopy = badCopyOf(str, 10);   // 复制后只能为object类，会丢失原有类型
        System.out.println("badCopyOf中新数组大小 = " + newStrBadCopy.length);

        String[] newStrGoodCopy = (String[]) goodCopyOf(str, 10);   // 复制后只能为object类，会丢失原有类型
        System.out.println("goodCopyOf中新数组大小 = " + newStrBadCopy.length);

        System.out.println(Array.get(newStrGoodCopy, 2));

    }
}
